<template>
    <div class="table-container">

        <!-- 筛选条件 -->
        <el-card class="filter-card">
            <el-form :model="filterForm" :inline="true">
                <el-form-item label="主目录分类">
                    <el-input 
                        v-model="filterForm.category" 
                        placeholder="请输入分类关键词搜索" 
                        clearable 
                        style="width: 120px;"
                        @input="handleCategorySearch"
                        @clear="handleCategoryClear">
                        <template #prefix>
                            <el-icon><Search /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="filterForm.status" placeholder="请选择" clearable style="width: 120px;">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="启用" value="启用"></el-option>
                        <el-option label="禁用" value="禁用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleFilter">确认筛选</el-button>
                    <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格 -->
        <el-card class="table-card">
            <el-table :data="tableData" border>
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="category" label="主目录分类" width="150"></el-table-column>
                <el-table-column prop="sort" label="购物网站排序" width="120"></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container"
                style="display: flex; justify-content: space-between; align-items: center;">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    style="margin-top: 20px; text-align: right;" />
                <el-button type="primary" @click="handleAdd">新增</el-button>
            </div>
        </el-card>

        <!-- 弹框 修改-新增 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form :model="form" ref="formRef" label-width="120px">
                <el-form-item label="主目录分类" prop="category">
                    <el-select v-model="form.category" placeholder="请选择" style="width: 100%">
                        <el-option label="电子产品" value="电子产品"></el-option>
                        <el-option label="服装鞋帽" value="服装鞋帽"></el-option>
                        <el-option label="家居用品" value="家居用品"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="购物网站排序" prop="sort">
                    <el-input-number v-model="form.sort" :min="1" style="width: 100%"></el-input-number>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio label="启用">启用</el-radio>
                        <el-radio label="禁用">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 防抖函数
const debounce = (func, wait) => {
    let timeout
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout)
            func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
    }
}

// 筛选表单
const filterForm = reactive({
    category: '',
    status: ''
})

// 表格数据
const tableData = ref([])

// 分页
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

// 表单
const form = reactive({
    id: null,
    category: '',
    sort: 1,
    status: '启用'
})

// 模拟数据
const mockData = [
    { id: 1, category: '电子产品', sort: 1, status: '启用' },
    { id: 2, category: '服装鞋帽', sort: 2, status: '启用' },
    { id: 3, category: '家居用品', sort: 3, status: '禁用' },
    { id: 4, category: '食品饮料', sort: 4, status: '启用' },
    { id: 5, category: '运动户外', sort: 5, status: '禁用' },
    { id: 6, category: '母婴用品', sort: 6, status: '启用' },
    { id: 7, category: '美妆个护', sort: 7, status: '启用' },
    { id: 8, category: '汽车用品', sort: 8, status: '禁用' },
    { id: 9, category: '图书音像', sort: 9, status: '启用' },
    { id: 10, category: '家用电器', sort: 10, status: '禁用' },
    { id: 11, category: '办公用品', sort: 11, status: '启用' },
    { id: 12, category: '宠物用品', sort: 12, status: '启用' },
    { id: 13, category: '乐器', sort: 13, status: '禁用' },
    { id: 14, category: '医疗保健', sort: 14, status: '启用' },
    { id: 15, category: '家装建材', sort: 15, status: '禁用' },
    { id: 16, category: '数码配件', sort: 16, status: '启用' },
    { id: 17, category: '农资绿植', sort: 17, status: '启用' },
    { id: 18, category: '珠宝饰品', sort: 18, status: '禁用' },
    { id: 19, category: '玩具乐器', sort: 19, status: '启用' },
    { id: 20, category: '二手商品', sort: 20, status: '禁用' },
    { id: 21, category: '电子产品', sort: 21, status: '禁用' },
    { id: 22, category: '服装鞋帽', sort: 22, status: '禁用' },
    { id: 23, category: '家居用品', sort: 23, status: '启用' },
    { id: 24, category: '食品饮料', sort: 24, status: '禁用' },
    { id: 25, category: '运动户外', sort: 25, status: '启用' },
    { id: 26, category: '母婴用品', sort: 26, status: '禁用' },
    { id: 27, category: '美妆个护', sort: 27, status: '禁用' },
    { id: 28, category: '汽车用品', sort: 28, status: '启用' },
    { id: 29, category: '图书音像', sort: 29, status: '禁用' },
    { id: 30, category: '家用电器', sort: 30, status: '启用' },
]

// 初始化
onMounted(() => {
    loadData()
})

// 加载数据
const loadData = () => {
    let filteredData = [...mockData]

    if (filterForm.category) {
        filteredData = filteredData.filter(item => 
            item.category.toLowerCase().includes(filterForm.category.toLowerCase())
        )
    }

    if (filterForm.status) {
        filteredData = filteredData.filter(item => item.status === filterForm.status)
    }

    pagination.total = filteredData.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    tableData.value = filteredData.slice(start, end)
}

// 筛选
const handleFilter = () => {
    pagination.currentPage = 1
    loadData()
    ElMessage.success('筛选成功')
}

// 分类搜索处理（防抖）
const handleCategorySearch = debounce(() => {
    pagination.currentPage = 1
    loadData()
}, 300)

// 分类搜索清空处理
const handleCategoryClear = () => {
    pagination.currentPage = 1
    loadData()
}

// 重置筛选
const resetFilter = () => {
    filterForm.category = ''
    filterForm.status = ''
    pagination.currentPage = 1
    loadData()
    ElMessage.info('已重置')
}

// 新增
const handleAdd = () => {
    dialogTitle.value = '新增数据'
    dialogVisible.value = true
    Object.assign(form, { id: null, category: '', sort: 1, status: '启用' })
}

// 编辑
const handleEdit = (row) => {
    dialogTitle.value = '编辑数据'
    dialogVisible.value = true
    Object.assign(form, row)
}

// 删除
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除ID为${row.id}的数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = mockData.findIndex(item => item.id === row.id)
        if (index > -1) {
            mockData.splice(index, 1)
            loadData()
            ElMessage.success('删除成功')
        }
    })
}

// 提交
const handleSubmit = () => {
    if (form.id) {
        // 编辑
        const index = mockData.findIndex(item => item.id === form.id)
        if (index > -1) {
            Object.assign(mockData[index], { ...form })
        }
        ElMessage.success('编辑成功')
    } else {
        // 新增
        const newId = Math.max(...mockData.map(item => item.id)) + 1
        mockData.push({ id: newId, ...form })
        ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    loadData()
}

// 分页
const handleSizeChange = (val) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    loadData()
}

const handleCurrentChange = (val) => {
    pagination.currentPage = val
    loadData()
}
</script>

<style scoped>
.table-container {
    padding: 20px;
}

.filter-card,
.action-card,
.table-card {
    margin-bottom: 20px;
}

:deep(.filter-card .el-card__body) {
    padding-bottom: 0 !important;
}
</style>
